package com.bachongLightNovel.utils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.ZoneOffset;

/**
 *
 * 全局id生成器
 * @author vermouth
 */

@Component
public class GlobalIdWorker {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    //开始时间戳，此处为 2024-1-1 0:0:0的时间戳
    private final long BEGIN_TIME=1717200000;

    /**
     * 全局id生成方法，利用redis实现
     * @param prefix: 
     * @return long
     * @author vermouth
     */      
    public long generateId(String prefix){
        //获取当前时间戳
        long nowTimestamp = LocalDateTime.now().toEpochSecond(ZoneOffset.UTC);
        long timestamp=nowTimestamp-BEGIN_TIME;
        Long count = stringRedisTemplate.opsForValue().increment(prefix);
        return timestamp<<32|count;
    }
}
